﻿using Global;
using IPlugins;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SamplePlugin
{
    /// <summary>
    /// 将此插件生成的dll放入到运行根目录下plugins.config.json中配置的指定路径
    /// </summary>
    public class SamplePlugin : IPlugins.IPlugin, IPluginConfiguration
    {
        private IPluginHost _host;
        private Form _pluginForm;
        private Button _btnPublishEvent;
        private TextBox _txtConfigValue;

        // 插件配置
        public string ConfigValue { get; set; } = "哈哈哈哈";

        public string Name { get { return "Sample Plugin"; } }
        public string Description { get { return "测试插件1"; } }
        public bool IsEnabled { get; set; }

        public SamplePlugin()
        {
        }

        public void Initialize(IPluginHost host)
        {
            _host = host;
            // 注册插件函数
            _host.RegisterFunction("GetPluginInfo", new Func<string>(() => string.Format("{0}: {1}", Name, Description)));
            // 订阅事件
            EventBus.Subscribe("DataUpdated", OnDataUpdated);
            Execute();
        }

        private void OnDataUpdated(object data)
        {
            if (_pluginForm != null && !_pluginForm.IsDisposed)
            {
                _pluginForm.Invoke(new Action(() =>
                {
                    MessageBox.Show(string.Format("Received event with data: {0}", data), "Event Received");
                }));
            }
        }

        public void Execute()
        {
            _pluginForm = _host.CreateSandboxForm();
            _pluginForm.Text = $"{Name}: {ConfigValue}";
            _pluginForm.Size = new Size(400, 300);

            // 事件发布按钮
            _btnPublishEvent = new Button
            {
                Text = "Publish Event",
                Dock = DockStyle.Top
            };
            _btnPublishEvent.Click += (s, e) =>
            {
                EventBus.Publish("SampleEvent", new { Sender = Name, Time = DateTime.Now,Msg =$"{Name}发布了一条消息" });
                _host.CallFunction("ShowHostMessage", "Event published!");
            };

            // 状态标签
            var lblStatus = new System.Windows.Forms.Label
            {
                Text = $"Current config: {ConfigValue}",
                Dock = DockStyle.Top,
                TextAlign = ContentAlignment.MiddleCenter
            };

            _pluginForm.Controls.AddRange(new Control[] { _btnPublishEvent, lblStatus });

            // 显示窗体
            _host.MainForm.Invoke(new Action(() =>
            {
                _pluginForm.MdiParent = _host.MainForm;
                _pluginForm.Show();
            }));
        }

        public void Shutdown()
        {
            if (_pluginForm != null && !_pluginForm.IsDisposed)
            {
                _pluginForm.Invoke(new Action(() => _pluginForm.Close()));
            }

            // 取消事件订阅
            EventBus.Unsubscribe("DataUpdated", OnDataUpdated);
        }

        #region 插件配置实现
        public UserControl GetConfigurationControl()
        {
            var control = new UserControl();
            control.Dock = DockStyle.Fill;

            _txtConfigValue = new TextBox
            {
                Text = ConfigValue,
                Dock = DockStyle.Top
            };

            var lblInfo = new System.Windows.Forms.Label
            {
                Text = "Plugin Configuration Value:",
                Dock = DockStyle.Top
            };

            control.Controls.AddRange(new Control[] { _txtConfigValue, lblInfo });
            return control;
        }

        public void SaveConfiguration()
        {
            ConfigValue = _txtConfigValue.Text;

            // 更新UI反映新配置
            if (_pluginForm != null && !_pluginForm.IsDisposed)
            {
                _pluginForm.Invoke(new Action(() =>
                {
                    _pluginForm.Text = string.Format("{0} - Config: {1}", Name, ConfigValue);
                    foreach (Control ctrl in _pluginForm.Controls)
                    {
                        if (ctrl is System.Windows.Forms.Label && ((System.Windows.Forms.Label)ctrl).Text.StartsWith("Current config:"))
                        {
                            ((System.Windows.Forms.Label)ctrl).Text = string.Format("Current config: {0}", ConfigValue);
                        }
                    }
                }));
            }
        }
        #endregion
    }
}
